package com.shugl.study;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Description
 *
 * @author ShuGuili
 * @version 1.0
 * @since 2021/3/29 14:37
 */
public class BeanUtil {


    /**
     * 功能描述:通用转字符串 暂时没判断基础类型的包装类型，无限递归
     *
     * @param o
     * @return java.lang.String
     * @author shugl
     * @date 2021/3/29 14:38
     */
    public String toString(Object o) {
        if (o == null) {
            return null;
        }
        StringBuilder re = new StringBuilder();
        Class cl = o.getClass();
        // 字符串
        if (cl == String.class) {
            return (String) o;
        }
        // 数组
        if (cl.isArray()) {
            re.append("[");
            int max = Array.getLength(o);
            for (int i = 0; i < max; i++) {
                //是否是基本类型
                if (cl.getComponentType().isPrimitive()) {
                    re.append(Array.get(o, i));
                } else {
                    objToString(Array.get(o, i));
                }
                if (i == max - 1) {
                    re.append("]");
                } else {
                    re.append(", ");
                }
            }
            return re.toString();
        }
        // 对象
        return objToString(o);
    }

    /**
     * 功能描述: 对象转字符串
     *
     * @param o
     * @return void
     * @author shugl
     * @date 2021/3/29 15:57
     */
    public String objToString(Object o) {
        StringBuilder re = new StringBuilder("{");
        Class cl = o.getClass();
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        int size = fields.length;
        for (Field field : fields) {
            // 非静态域
            if (!Modifier.isStatic(field.getModifiers())) {
                try {
                    Class fClass = field.getType();
                    Field isPri = fClass.getField("TYPE");
                    if (fClass.isPrimitive()) {
                        re.append(field.get(o));
                    } else {
                        objToString(o);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                size--;
                if (size > 0) {
                    re.append(", ");
                }
            }
            cl = cl.getSuperclass();
        }
        re.append("}");
        return re.toString();
    }

}
